package codepulse.blogmoon.cn.code.controller;

import cn.hutool.core.util.DesensitizedUtil;
import codepulse.blogmoon.cn.code.dto.CodeAuthDetailDTO;
import codepulse.blogmoon.cn.code.entity.CodeAuthDetail;
import codepulse.blogmoon.cn.code.service.CodeAuthDetailService;
import codepulse.blogmoon.cn.common.context.Context;
import codepulse.blogmoon.cn.common.entity.PageReq;
import codepulse.blogmoon.cn.common.entity.PageResult;
import codepulse.blogmoon.cn.common.entity.Result;
import codepulse.blogmoon.cn.common.utils.BaseConvert;
import codepulse.blogmoon.cn.common.utils.PageUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/codeAuthDetail")
public class CodeAuthDetailController {

    @Resource
    private CodeAuthDetailService codeAuthDetailService;

    @PostMapping("/save")
    public Result saveCodeHost(@RequestBody CodeAuthDetailDTO codeAuthDetail) {
        CodeAuthDetail authDetail = BaseConvert.convert(codeAuthDetail, CodeAuthDetail.class);
        authDetail.setTeamId(Context.get().getTeamId());
        authDetail.setCreateField();
        codeAuthDetailService.save(authDetail);
        return Result.success();
    }

    @PostMapping("/pageList")
    public Result pageList(@RequestBody PageReq pageReq) {
        Page<CodeAuthDetail> page = codeAuthDetailService.page(new Page<>(pageReq.getPageNo(), pageReq.getPageSize()),
                Wrappers.<CodeAuthDetail>lambdaQuery()
                        .eq(CodeAuthDetail::getTeamId, Context.get().getTeamId()));
        PageResult<CodeAuthDetailDTO> pageResult = PageUtil.getPage(page, item -> {
            CodeAuthDetailDTO dto = BaseConvert.convert(item, CodeAuthDetailDTO.class);
            dto.setMaskSecret(DesensitizedUtil.password(dto.getSecret()));
            return dto;
        });
        return Result.success(pageResult);
    }
}
